package cn.tedu.kcircle.security.support.handler;

import cn.tedu.kcircle.common.restful.JsonResult;
import cn.tedu.kcircle.common.restful.ResponseCode;
import cn.tedu.kcircle.common.util.CustomResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        //处理未通过认证情况下 向需要通过认证的资源发起请求导致401错误的问题
        String message = "操作失败，您当前未登录，或登录已过期！";
        log.error(message,authException);
        JsonResult jsonResult = JsonResult.failed(ResponseCode.ERROR_UNAUTHORIZED, message);
        CustomResponse.sendResponse(response,jsonResult);
    }
}
